//this file is part of eMule
//Copyright (C)2002 Merkur ( merkur-@users.sourceforge.net / http://www.emule-project.net )
//
//This program is free software; you can redistribute it and/or
//modify it under the terms of the GNU General Public License
//as published by the Free Software Foundation; either
//version 2 of the License, or (at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program; if not, write to the Free Software
//Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.


// ServerWnd.cpp : implementation file
//

//#include "stdafx.h"
#include "wintypes.h"
#include "emule.h"
#include "ServerWnd.h"
//#include "HttpDownloadDlg.h"
#include "HTTPDownloadDlg.h"
#include "config.h"

// CServerWnd dialog
#include "muuli_wdr.h"

//IMPLEMENT_DYNAMIC(CServerWnd, CDialog)
IMPLEMENT_DYNAMIC_CLASS(CServerWnd,wxPanel)

BEGIN_EVENT_TABLE(CServerWnd,wxPanel)
  EVT_BUTTON(ID_ADDTOLIST,CServerWnd::OnBnClickedAddserver)
  EVT_BUTTON(ID_UPDATELIST,CServerWnd::OnBnClickedUpdateservermetfromurl)
END_EVENT_TABLE()

#include <wx/textctrl.h>

CServerWnd::CServerWnd(wxWindow* pParent /*=NULL*/)
  : wxPanel(pParent,CServerWnd::IDD)
{
  SetBackgroundColour(GetColour(wxSYS_COLOUR_WINDOW));
  wxSizer* content=serverListDlg(this,TRUE);
  content->Show(this,TRUE);

  // init serverlist
  // no use now. too early.
  CServerListCtrl* list=(CServerListCtrl*)wxFindWindowByName("serverListCtrl");
  //list->Init(theApp.serverlist);
  serverlistctrl=list;

  wxTextCtrl* cv=(wxTextCtrl*)FindWindowByName("serverInfo");
  cv->AppendText(wxString(_("This is "))+wxString(PACKAGE)+wxString(" ")+wxString(VERSION)+wxString(_(" (based on "))+wxString(_("eMule v"))+wxString(CURRENT_VERSION_LONG)+wxString(")\n"));
  cv->AppendText(wxString(_("Visit http://lmule.sf.net to check if a new version is available.")));
//  cv->AppendText(GetResString(IDS_EMULEW)+wxString(" "));
//  cv->AppendText(GetResString(IDS_EMULEW3)+wxString(" "));
//  cv->AppendText(GetResString(IDS_EMULEW2)+wxString("\n\n"));
}

CServerWnd::~CServerWnd(){
}


#if 0
BOOL CServerWnd::OnInitDialog(){
	CResizableDialog::OnInitDialog();
	Localize();
	SetWindowLong(GetDlgItem(IDC_IPADDRESS)->m_hWnd,GWL_STYLE,WS_CHILD|WS_VISIBLE);
	SetWindowLong(GetDlgItem(IDC_IPADDRESS)->m_hWnd,GWL_EXSTYLE,WS_EX_STATICEDGE);
	serverlistctrl.Init(theApp.serverlist);
	
	m_ctrlNewServerFrm.Init(IDI_NEWSERVER);
	m_ctrlUpdateServerFrm.Init(IDI_UPDATESERVERS);
	((CStatic*)GetDlgItem(IDC_SERVLST_ICO))->SetIcon((HICON)::LoadImage(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDI_SERVERLIST), IMAGE_ICON, 16, 16, 0));
	((CStatic*)GetDlgItem(IDC_SERVINF_ICO))->SetIcon((HICON)::LoadImage(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDI_SERVERINFO), IMAGE_ICON, 16, 16, 0));
	((CStatic*)GetDlgItem(IDC_LOG_ICO))->SetIcon((HICON)::LoadImage(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDI_LOG), IMAGE_ICON, 16, 16, 0));

	((CEdit*)GetDlgItem(IDC_SPORT))->SetLimitText(5);
	GetDlgItem(IDC_SPORT)->SetWindowText("4661");
	CRect rect;

	GetDlgItem(IDC_SERVMSG)->GetWindowRect(rect);
	::MapWindowPoints(NULL, m_hWnd, (LPPOINT)&rect, 2);
	servermsgbox.CreateEx(WS_EX_STATICEDGE,0,"MsgWnd",WS_VISIBLE | WS_CHILD | HTC_WORDWRAP |HTC_AUTO_SCROLL_BARS | HTC_UNDERLINE_HOVER,rect.left,rect.top,rect.Width(),rect.Height(),m_hWnd,0);
	
	servermsgbox.AppendText(CString(CString("eMule v")+CString(CURRENT_VERSION_LONG)+CString("\n")));
	servermsgbox.AppendText(GetResString(IDS_EMULEW)+CString(" "),false);
	CString strLink;
	strLink.Format("http://www.emule-project.net/en/version_check.php?version=%i&language=%i",CURRENT_VERSION_CHECK,theApp.glob_prefs->GetLanguageID());
	servermsgbox.AppendHyperLink(GetResString(IDS_EMULEW3)+CString(" "),0,strLink,0,false);
	servermsgbox.AppendText(GetResString(IDS_EMULEW2),false);
	servermsgbox.AppendText(CString("\n\n"));
	
	AddAnchor(IDC_SERVLIST,TOP_LEFT,CSize(100,34));
	AddAnchor(IDC_SERVINF_TEXT,CSize(0,34));
	AddAnchor(IDC_SERVINF_ICO,CSize(0,34));
	AddAnchor(servermsgbox,CSize(0,34),CSize(100,60));
	AddAnchor(IDC_LOG_TEXT,CSize(0,60));
	AddAnchor(IDC_LOG_ICO,CSize(0,60));
	AddAnchor(IDC_LOGBOX,CSize(0,60),BOTTOM_RIGHT);
	AddAnchor(IDC_SSTATIC,TOP_RIGHT);
	AddAnchor(IDC_SSTATIC4,TOP_RIGHT);
	AddAnchor(IDC_SSTATIC7,TOP_RIGHT);
	AddAnchor(IDC_IPADDRESS,TOP_RIGHT);
	AddAnchor(IDC_SSTATIC3,TOP_RIGHT);
	AddAnchor(IDC_SNAME,TOP_RIGHT);
	AddAnchor(IDC_ADDSERVER,TOP_RIGHT);
	AddAnchor(IDC_SBUTTON1,TOP_RIGHT);
	AddAnchor(IDC_SSTATIC5,TOP_RIGHT);
	AddAnchor(IDC_SPORT,TOP_RIGHT);
	AddAnchor(IDC_SSTATIC6,TOP_RIGHT);
	AddAnchor(IDC_SERVERMETURL,TOP_RIGHT);
	AddAnchor(IDC_UPDATESERVERMETFROMURL,TOP_RIGHT);
	AddAnchor(IDC_LOGRESET,CSize(100,60));
	return true;
}

void CServerWnd::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_SERVLIST, serverlistctrl);
	//	DDX_Control(pDX, IDC_EDIT1, servermsgbox);

	DDX_Control(pDX, IDC_LOGBOX, logbox);
	DDX_Control(pDX, IDC_SSTATIC, m_ctrlNewServerFrm);
	DDX_Control(pDX, IDC_SSTATIC6, m_ctrlUpdateServerFrm);
}
#endif

void CServerWnd::UpdateServerMetFromURL(wxString strURL) {
  if (strURL.Find("://") == -1)	// not a valid URL
    {
      theApp.emuledlg->AddLogLine(true, GetResString(IDS_INVALIDURL) );
      return;
    }
  
  wxString strTempFilename;
  strTempFilename=wxString::Format("%stemp-%d-server.met", theApp.glob_prefs->GetAppDir(), ::GetTickCount());
  
  CHTTPDownloadDlg *dlg=new CHTTPDownloadDlg(this,strURL,strTempFilename);
  int retval=dlg->ShowModal();
  if(retval==0) {
    // wget succeeded. proceed with serverlist processing
    serverlistctrl->AddServermetToList(strTempFilename);
    remove(strTempFilename);
    theApp.serverlist->SaveServermetToFile();
  } else {
      theApp.emuledlg->AddLogLine(true, GetResString(IDS_ERR_FAILEDDOWNLOADMET).GetData(), strURL.GetData());
  }
  delete dlg;

#if 0
  // step2 - try to download server.met
  CHttpDownloadDlg dlgDownload;
  dlgDownload.m_sURLToDownload = strURL;
  dlgDownload.m_sFileToDownloadInto = strTempFilename;
  if (dlgDownload.DoModal() != IDOK)
    {
      theApp.emuledlg->AddLogLine(true, GetResString(IDS_ERR_FAILEDDOWNLOADMET), strURL);
      return;
    }
  
  // step3 - add content of server.met to serverlis
  serverlistctrl.Hide();
  serverlistctrl.AddServermetToList(strTempFilename);
  serverlistctrl.Visable();
  remove(strTempFilename);
  theApp.serverlist->SaveServermetToFile();
#endif
}

void CServerWnd::Localize() {
#if 0
	serverlistctrl.Localize();

	GetDlgItem(IDC_SERVLIST_TEXT)->SetWindowText(GetResString(IDS_SV_SERVERLIST));
	GetDlgItem(IDC_SERVINF_TEXT)->SetWindowText(GetResString(IDS_SV_SERVERINFO));
	GetDlgItem(IDC_LOG_TEXT)->SetWindowText(GetResString(IDS_SV_LOG));
	GetDlgItem(IDC_SSTATIC)->SetWindowText(GetResString(IDS_SV_NEWSERVER));
	GetDlgItem(IDC_SSTATIC4)->SetWindowText(GetResString(IDS_SV_ADDRESS));
	GetDlgItem(IDC_SSTATIC7)->SetWindowText(GetResString(IDS_SV_PORT));
	GetDlgItem(IDC_SSTATIC3)->SetWindowText(GetResString(IDS_SW_NAME));
	GetDlgItem(IDC_ADDSERVER)->SetWindowText(GetResString(IDS_SV_ADD));
	GetDlgItem(IDC_SSTATIC6)->SetWindowText(GetResString(IDS_SV_MET));
	GetDlgItem(IDC_UPDATESERVERMETFROMURL)->SetWindowText(GetResString(IDS_SV_UPDATE));
	GetDlgItem(IDC_LOGRESET)->SetWindowText(GetResString(IDS_PW_RESET));
#endif
}

#if 0
BEGIN_MESSAGE_MAP(CServerWnd, CResizableDialog)
	ON_BN_CLICKED(IDC_ADDSERVER, OnBnClickedAddserver)
	ON_BN_CLICKED(IDC_UPDATESERVERMETFROMURL, OnBnClickedUpdateservermetfromurl)
	ON_BN_CLICKED(IDC_LOGRESET, OnBnClickedResetLog)
END_MESSAGE_MAP()

#endif
// CServerWnd message handlers

void CServerWnd::OnBnClickedAddserver(wxEvent& evt){
  wxString serveraddr;
  if(((wxTextCtrl*)FindWindowByName("ipAddress"))->GetLineText(0).IsEmpty()) {
    //if (!GetDlgItem(IDC_IPADDRESS)->GetWindowTextLength()){
    theApp.emuledlg->AddLogLine(true, GetResString(IDS_SRV_ADDR) );
    return;
  }
  else
    serveraddr=((wxTextCtrl*)FindWindowByName("ipAddress"))->GetLineText(0);
  //GetDlgItem(IDC_IPADDRESS)->GetWindowText(serveraddr);
  
  //if (!GetDlgItem(IDC_SPORT)->GetWindowTextLength()){
  if(((wxTextCtrl*)FindWindowByName("portNumber"))->GetLineText(0).IsEmpty()) {
    theApp.emuledlg->AddLogLine(true, GetResString(IDS_SRV_PORT) );
    return;
  }
  
  //char portstr[6];
  //GetDlgItem(IDC_SPORT)->GetWindowText(portstr,6);
  wxString portstr;
  portstr=((wxTextCtrl*)FindWindowByName("portNumber"))->GetLineText(0);
  CServer* toadd = new CServer(atoi(portstr.GetData()),(char*)serveraddr.GetData());
  
  //int32 namelen = GetDlgItem(IDC_SNAME)->GetWindowTextLength();
  wxString servername;
  servername=((wxTextCtrl*)FindWindowByName("serverName"))->GetLineText(0);
  if (!servername.IsEmpty()){
    //char* servername = new char[namelen+2];
    //GetDlgItem(IDC_SNAME)->GetWindowText(servername,namelen+1);
    toadd->SetListName((char*)servername.GetData());
    //delete[] servername;
  }
  else{
    toadd->SetListName((char*)serveraddr.GetData());
  }
  if (!serverlistctrl->AddServer(toadd,true)){
    CServer* update = theApp.serverlist->GetServerByAddress(toadd->GetAddress(), toadd->GetPort());
    if(update){
      update->SetListName(toadd->GetListName());
      serverlistctrl->RefreshServer(update);
    }
    delete toadd;
    theApp.emuledlg->AddLogLine(true, GetResString(IDS_SRV_NOTADDED) );
  } else theApp.emuledlg->AddLogLine(true,GetResString(IDS_SERVERADDED)+wxString(toadd->GetListName()));
  theApp.serverlist->SaveServermetToFile();
}

void CServerWnd::OnBnClickedUpdateservermetfromurl(wxEvent& evt)
{
  wxString strURL;
  strURL=((wxTextCtrl*)FindWindowByName("serverlistURL"))->GetLineText(0);

  UpdateServerMetFromURL(strURL);

#if 0
  wxString strURL;
  strURL=((wxTextCtrl*)FindWindowByName("serverlistURL"))->GetLineText(0);
  if(strURL=="") {
    if (!theApp.glob_prefs->adresses_list.IsEmpty()) 
      strURL=(wxString)theApp.glob_prefs->adresses_list.GetFirst()->GetData();
    else {
      theApp.emuledlg->AddLogLine(true, GetResString(IDS_SRV_NOURLAV) );
      return;
    }
  }
  UpdateServerMetFromURL(strURL);
#endif
}

#if 0
void CServerWnd::OnBnClickedResetLog() {theApp.emuledlg->ResetLog(); }
#endif

void CServerWnd::UpdateMyInfo() {
#if 0
	CString buffer;

	MyInfoList->DeleteAllItems();
	MyInfoList->InsertItem(0,GetResString(IDS_STATUS)+":");
	if (theApp.serverconnect->IsConnected())
		MyInfoList->SetItemText(0, 1, GetResString(IDS_CONNECTED ));
	else MyInfoList->SetItemText(0, 1, GetResString(IDS_DISCONNECTED )); 

	if (theApp.serverconnect->IsConnected()) {
		MyInfoList->InsertItem(1,GetResString(IDS_IP) +":"+GetResString(IDS_PORT) );
		if (theApp.serverconnect->IsLowID()) buffer=GetResString(IDS_UNKNOWN); else {
			uint32 myid=theApp.serverconnect->GetClientID();
			uint8 d=myid/(256*256*256);myid-=d*(256*256*256);
			uint8 c=myid/(256*256);myid-=c*256*256;
			uint8 b=myid/(256);myid-=b*256;
			buffer.Format("%i.%i.%i.%i:%i",myid,b,c,d,theApp.glob_prefs->GetPort());
		}
		MyInfoList->SetItemText(1,1,buffer);

		buffer.Format("%u",theApp.serverconnect->GetClientID());
		MyInfoList->InsertItem(2,GetResString(IDS_ID));
		if (theApp.serverconnect->IsConnected()) MyInfoList->SetItemText(2, 1, buffer); 

		MyInfoList->InsertItem(3,"");
		if (theApp.serverconnect->IsLowID()) MyInfoList->SetItemText(3, 1,GetResString(IDS_IDLOW));
			else MyInfoList->SetItemText(3, 1,GetResString(IDS_IDHIGH));
	}
#endif
	printf("TODO: MyInfo @ CServerWnd (GUI missing)\n");
}
